package mz.co.research.server.mvc.model.dao.jpa;

import java.util.Collection;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import mz.co.framework.error.DaoException;
import mz.co.research.shared.model.AnswerType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository("answerTypeJpaDao")
public class AnswerTypeJpaDao extends AbstractJpaDao<Long, AnswerType> {

	@Autowired
	EntityManagerFactory entityManagerFactory;

	@PostConstruct
	public void init() {
		super.setEntityManagerFactory(entityManagerFactory);
	}

	public AnswerType findByType(String type) throws DaoException {

		CriteriaBuilder cb = entityManagerFactory.getCriteriaBuilder();

		CriteriaQuery<AnswerType> q = cb.createQuery(AnswerType.class);
		Root<AnswerType> from = q.from(AnswerType.class);

		q.select(from).where(cb.equal(from.get("type"), type),
				cb.equal(from.get("active"), true));

		return findByUnique(q);

	}

	public Collection<AnswerType> findByActive(boolean active)
			throws DaoException {

		CriteriaBuilder cb = entityManagerFactory.getCriteriaBuilder();

		CriteriaQuery<AnswerType> q = cb.createQuery(AnswerType.class);
		Root<AnswerType> from = q.from(AnswerType.class);

		q.select(from).where(cb.equal(from.get("active"), active));

		return findByQuery(q);

	}

}
